# 计算总成绩
import os

class Score:
    def __init__(self, name):
        self._score = self._load_data(name)

    def show(self):
        for s in self._score:
            print(s)

    def calc_total(self):
        for s in self._score:
            total = 0
            for key in s:
                if key != "name":
                    total += s[key]
            s["total"] = total

    def save(self, name):
        with open(f"{os.path.dirname(__file__)}/{name}", "w", encoding="utf8") as data:
            data.write("# 姓名 语文 英语 数学 道法 科学 总分\n")
            for s in self._score:
                data.write(f"{s['name']:4}\t{s['chinese']:>6.1f}{s['english']:>6.1f}{s['math']:>6.1f}{s['moral']:>6.1f}{s['science']:>6.1f}{s['total']:>7.1f}\n")

    def _load_data(self, name):
        scores = []
        with open(f"{os.path.dirname(__file__)}/{name}", "r", encoding="utf8") as data:
            line = data.readline()
            while line:
                if line.startswith("#"):
                    pass
                else:
                    items = line.split()
                    s = {
                        "name":    items[0],
                        "chinese": float(items[1]),
                        "english": float(items[2]),
                        "math":    float(items[3]),
                        "moral":   float(items[4]),
                        "science": float(items[5])
                    }
                    scores.append(s)
                
                # 读取下一行
                line = data.readline()
        return scores

if __name__ == "__main__":
    objScore = Score("data_68.txt")
    objScore.calc_total()
    objScore.show()
    objScore.save("data_total.txt")


